import { HttpException, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { AuthEntity } from '../entitys/auth.entity';
import { Connection, Repository } from 'typeorm';

@Injectable()
export class AuthService {
  constructor(
    @InjectRepository(AuthEntity)
    private readonly authRepository: Repository<AuthEntity>,
    private connection: Connection,
  ) {}

  // 获取权限列表
  async getAuthListService() {
    const oneMenuSql =
      "SELECT f_id as id, f_name as label, f_url as url, f_sort as sort, f_pid as pId FROM t_author WHERE f_pid = '0'";
    const oneMenuResult = await this.authRepository.query(oneMenuSql);

    const twoMenuSql =
      'SELECT f_id as id, f_name as label, f_url as url, f_sort as sort, f_pid as pId FROM t_author WHERE f_pid = ?';

    for (let oneMenuItem of oneMenuResult) {
      oneMenuItem['children'] = [];
      const twoMenuResult = await this.authRepository.query(
        twoMenuSql,
        oneMenuItem.id,
      );
      oneMenuItem.children.push(...twoMenuResult);
    }
    return oneMenuResult;
  }

  // 根据RoleId获取对应权限
  async getAuthByRoleIdServe(roleId) {
    const sql = `SELECT r.f_id as roleId, a.f_id as authId, a.f_name as authName 
                  FROM t_role r 
                  INNER JOIN t_role_auth rt ON r.f_id = rt.f_role_id
                  INNER JOIN t_author a  ON rt.f_auth_id = a.f_id
                  WHERE r.f_id = ?`;
    return await this.authRepository.query(sql, roleId);
  }

  // 根据RoleId修改权限
  async updateAuthRoleIdServe(RoleAuth) {
    const queryRunner = this.connection.createQueryRunner();

    await queryRunner.connect();
    await queryRunner.startTransaction();
    try {
      const sql1 = 'DELETE FROM t_role_auth WHERE f_role_id = ?';
      const sql2 = 'INSERT INTO t_role_auth(f_role_id,f_auth_id) VALUES(?,?)';
      await queryRunner.manager.query(sql1, RoleAuth.fRoleId);
      for (const item of RoleAuth.fAuthArray) {
        await queryRunner.manager.query(sql2, [RoleAuth.fRoleId, item]);
      }
      await queryRunner.commitTransaction();
      return {
        message: '权限修改成功',
      };
    } catch (err) {
      throw new HttpException('权限修改失败', err.errno);
    }
  }

  // 修改权限
  async updateAuthConServe(updateAuthCon) {
    const { fAuthId, fAuthName, fAuthUrl, fAuthSort } = updateAuthCon;
    const sql = 'UPDATE t_author SET f_name=?,f_url=?,f_sort=? WHERE f_id=?';
    return this.authRepository.query(sql, [
      fAuthName,
      fAuthUrl,
      fAuthSort,
      fAuthId,
    ]);
  }

  // 新增下级
  async addChildAuthServe(AddAuthCon) {
    const { fAuthName, fAuthUrl, fPId } = AddAuthCon;
    const sql = 'INSERT INTO t_author(f_name,f_url,f_pid) VALUE(?,?,?)';
    return await this.authRepository.query(sql, [fAuthName, fAuthUrl, fPId]);
  }

  // 删除权限
  async deleteAuthServe(deleteCon) {
    const { fAuthId } = deleteCon;
    const sql = 'DELETE FROM t_author WHERE f_id = ?';
    return this.authRepository.query(sql, fAuthId);
  }
}
